package HttpServer;


import Command.SetCommand;
import Executor.DbThreadExecutor;
import HttpServer.Response.JSONSerializer;
import HttpServer.Response.ResponseObject;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

public class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }


    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {

        String uri = req.uri();
        HttpMethod method = req.method();

        //解析uri参数
        QueryStringDecoder queryDecoder = new QueryStringDecoder(uri, CharsetUtil.UTF_8);
        Map<String, List<String>> uriAttributes = queryDecoder.parameters();

        //获取 KEY VALUE

        String key = "";
        String value ="";
        String ExpireTime = "";
        switch (queryDecoder.path()){
            case "/putWithExpireTime" :
                key = uriAttributes.get("key").get(0);
                value = uriAttributes.get("value").get(0);
                ExpireTime = uriAttributes.get("expiretime").get(0);
                break;
            case "/put":
                key = uriAttributes.get("key").get(0);
                value = uriAttributes.get("value").get(0);
                ExpireTime = "-1";
                break;
            case "/get"  :
                key = uriAttributes.get("key").get(0);
                break;
        }

        //响应对象构造
        ResponseObject res = new ResponseObject();
        res.setMethod(req.method().name());
        res.setUri(uri);
        res.setKey(key);
        res.setValue("");
        if(method.equals(HttpMethod.GET)) {
           // DbThreadExecutor.submitProducer(queryDecoder.path(),key, value,"-1") ;
            HttpServerClient.queue.push(new SetCommand(queryDecoder.path(),key,value,ExpireTime));
            System.out.println(res.toString());
        }


        //序列化对象
        byte[] content =  new JSONSerializer().serialize(res);

        // 创建http响应
        FullHttpResponse response = new DefaultFullHttpResponse(
                HttpVersion.HTTP_1_1,
                HttpResponseStatus.OK,
                Unpooled.wrappedBuffer(content)
        );


        // 设置头信息
        response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain; charset=UTF-8");
        response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH,response.content().readableBytes());
        //写入客户端
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);

    }



}
